/*eslint-disable*/

import React, {useState, useEffect} from 'react';
import {
  StyleSheet,
  Text,
  View,
  KeyboardAvoidingView,
  Platform,
  ImageBackground,
  Dimensions,
  SafeAreaView,
  TouchableHighlight,
  Alert,
} from 'react-native';
import {CodeField, Cursor} from 'react-native-confirmation-code-field';
import {Navigation} from 'react-native-navigation';
import {MainRoot} from '../navigation/index';

const {width, height} = Dimensions.get('window');
const second = 60;
const InputAuthCode = (props: any) => {
  const [vcodeTxt, setVcodeTxt] = useState('');
  const [active, setActive] = useState(false);
  const [timeId, setTimeId] = useState<any>();
  const [count, setCount] = useState(second);
  const submit = () => {
    if (!active) return;
    fetch('https://dog.ceo/api/breeds/image/random', {
      method: 'get',
    })
      .then(res => res.json())
      .then(res => {
        if (res.status === 'success') {
          // Navigation.dismissModal(props.componentId); #关闭模态框，回到之前页面
          Navigation.setRoot(MainRoot);
        } else {
          Alert.alert('登陆失败');
        }
      });
  };


  const changeTime = (time: number) => {
    const codeTime = time;
    let now = Date.now();
    const overTimeStamp = now + codeTime * 1000 + 100; // 100是时间容错
    setTimeId(
      setInterval(function () {
        const nowStap = Date.now();
        if (nowStap >= overTimeStamp) {
          clearInterval(timeId);
        } else {
          const leftTime = parseInt(String((overTimeStamp - nowStap) / 1000),10);
          setCount(leftTime)
        }
      }, 1000),
    );
  };
  useEffect(() => {
    const listener = {
      // 监听器，显示/隐藏时触发
      componentDidAppear: () => {
        changeTime(second);
      },
      componentDidDisappear: () => {
        timeId && clearInterval(timeId);
      },
    };
    // 注册监听器
    const unsubscribe = Navigation.events().registerComponentListener(
      listener,
      props.componentId,
    );
    return () => {
      unsubscribe.remove();
    };
  }, []);
  return (
    <KeyboardAvoidingView
      behavior={Platform.OS == 'ios' ? 'padding' : 'height'}
      style={styles.container}>
      <ImageBackground
        source={require('../assets/loginBg.jpg')}
        style={styles.bgImg}>
        <View style={styles.inputAuthCodePage}>
          <View style={styles.header}>
            <Text style={[styles.headerText, styles.headerText1]}>
              请输入验证码
            </Text>
            <Text style={styles.headerText}>
              已发送4位数验证码到+86
              <Text style={styles.headerTextCount}> {props.phoneVal}</Text>
            </Text>
          </View>
          <View>
            <SafeAreaView style={styles.root}>
              <CodeField
                value={vcodeTxt}
                onChangeText={val => {
                  setVcodeTxt(() => {
                    setActive(val.length === 4);
                    return val;
                  });
                }}
                // 输入密码框的个数
                cellCount={4}
                rootStyle={styles.codeFiledRoot}
                keyboardType="number-pad"
                textContentType="oneTimeCode"
                onSubmitEditing={submit}
                renderCell={({index, symbol, isFocused}) => (
                  <Text
                    key={index}
                    style={[styles.cell, isFocused && styles.focusCell]}>
                    {symbol || (isFocused ? <Cursor /> : null)}
                  </Text>
                )}
              />
            </SafeAreaView>
            <TouchableHighlight
              onPress={submit}
              activeOpacity={1}
              style={styles.btnWrap}>
              <View>
                <Text style={styles.btnText}>确定</Text>
              </View>
            </TouchableHighlight>
            <View>
              <Text
                style={styles.counts}
                onPress={() => {
                  if (count !== 0) return;           
                  setCount(second);
                  changeTime(second);
                }}>
                重新获取({count})
              </Text>
            </View>
          </View>
        </View>
      </ImageBackground>
    </KeyboardAvoidingView>
  );
};
InputAuthCode.options = {
  topBar: {
    visible: false,
  },
  statusBar: {
    visible: false,
  },
};
export default InputAuthCode;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    width,
    height,
  },
  bgImg: {
    flex: 1,
    width,
    height,
    resizeMode: 'cover',
    paddingHorizontal: 40,
  },
  inputAuthCodePage: {},
  header: {
    marginTop: 80,
  },
  headerText: {
    color: 'white',
    fontSize: 12,
    fontWeight: '700',
  },
  headerText1: {
    fontSize: 20,
    marginBottom: 15,
  },
  root: {padding: 20},
  title: {textAlign: 'center', fontSize: 30},
  codeFiledRoot: {marginTop: 20},
  // 里面每个密码小框的样式
  cell: {
    width: 50,
    height: 50,
    lineHeight: 38,
    fontSize: 24,
    borderWidth: 2,
    borderColor: '#ffffff40',
    textAlign: 'center',
    backgroundColor: 'rgba(0,0,0,0.4)',
    color: '#fff',
  },
  // 当里面的每个密码小框被选中之后的样式
  focusCell: {
    borderColor: '#fff',
  },
  btnWrap: {
    marginTop: 20,
    borderRadius: 25,
    paddingHorizontal: 30,
    paddingVertical: 15,
    backgroundColor: 'rgba(0,0,0,0.6)',
  },
  btnText: {
    color: 'white',
    textAlign: 'center',
    fontSize: 18,
  },
  counts: {
    textAlign: 'center',
    marginTop: 20,
    color: '#fff',
    textDecorationLine: 'underline',
  },
  headerTextCount: {
    fontSize: 16,
  },
});
